package com.wanxi.servlet;

import com.alibaba.fastjson2.JSONObject;
import com.wanxi.model.ResultModel;
import com.wanxi.model.UserModel;
import com.wanxi.service.UserService;
import com.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        2.得到前端的值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//        3.封装model
        UserModel userModel = new UserModel();
        userModel.setName(username);
        userModel.setPassword(password);
//        4.调用service
        UserService userService = new UserServiceImpl();
//        5.得到返回结果
        ResultModel resultModel = userService.login(userModel);
        if ("success".equals(resultModel.getMsg())) {
            req.getSession().setAttribute("username", username);
        }
//        6.返回给前端
        resp.getWriter().println(JSONObject.toJSONString(resultModel));
    }


}
